﻿#region Copyright(c) 2006 ZO, All right reserved.
// -----------------------------------------------------------------------------
// Copyright(c) 2006 ZO, All right reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
//   1.  Redistribution of source code must retain the above copyright notice,
//       this list of conditions and the following disclaimer.
//   2.  Redistribution in binary form must reproduce the above copyright
//       notice, this list of conditions and the following disclaimer in the
//       documentation and/or other materials provided with the distribution.
//   3.  The name of the author may not be used to endorse or promote products
//       derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
// EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
// PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
// OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
// WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
// OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// -----------------------------------------------------------------------------
#endregion


#region Using directives

using System;
using System.Text;

#endregion

namespace ZO.SmartCore.Standards.Unicode.Normalization
{
    /// <summary>
    /// Class that performs Normalization Form KC.
    /// </summary>
    public static class NFKC
    {

        #region Constructors

        #endregion

        #region Destructor

        #endregion

        #region Fields

        #endregion

        #region Events

        #endregion

        #region Operators

        #endregion

        #region Properties

        #endregion

        #region Methods
        /// <summary>
        /// Normalization the given string.
        /// </summary>
        /// <param name="text">The string to normalize.</param>
        /// <returns>The normalized string.</returns>
        public static string Normalize(string text)
        {
            if (String.IsNullOrEmpty(text))
            {
                throw new ArgumentNullException("text");
            } // if


            StringBuilder buffer = new StringBuilder(text);
            Normalize(buffer);
            return buffer.ToString();
        } // normalize

        /// <summary>
        /// Normalization the given string.
        /// </summary>
        /// <param name="text">The string to normalize, contains The normalized string on return.</param>
        public static void Normalize(StringBuilder text)
        {
            //StringBuilder work;
            //StringBuilder result;

            if ((text != null) && (text.Length != 0))
            {
                //Decompose
                text = Decompose(text);

                // Bring the stringbuffer into canonical order.
                Order(text);


                // Do the canonical composition.
                text = Compose(text);
            }

        } // normalize


        private static StringBuilder Decompose(StringBuilder text)
        {
            StringBuilder textOutput = new StringBuilder();

            char code;
            for (int i = 0; i < text.Length; i++)
            {
                code = text[i];

                // In Unicode 3.0, Hangul was defined as the block from U+AC00
                // to U+D7A3, however, since Unicode 3.2 the block extends until
                // U+D7AF. The decomposeHangul function only decomposes until
                // U+D7A3. Should this be changed?

                if (code >= 0xAC00 && code <= 0xD7AF)
                {
                    textOutput.Append(Hangul.Decompose(code));
                } // if
                else
                {
                    textOutput.Append(Decomposition.Decompose(code));
                }
            }
            return textOutput;

        }

        private static StringBuilder Order(StringBuilder text)
        {
            bool isOrdered = false;

            while (!isOrdered)
            {

                int lastCC = Combining.GetClass(text[0]);

                isOrdered = true;
                for (int i = 0; i < text.Length - 1; i++)
                {
                    int nextCC = Combining.GetClass(text[i + 1]);
                    if (nextCC != 0 && lastCC > nextCC)
                    {
                        for (int j = i + 1; j > 0; j--)
                        {
                            if (Combining.GetClass(text[j - 1]) <= nextCC)
                            {
                                break;
                            }
                            char t = text[j];
                            text[j] = text[j - 1];
                            text[j - 1] = t;
                            isOrdered = false;
                        }
                        nextCC = lastCC;
                    }
                    lastCC = nextCC;
                }
            }

            return text;
        }
        private static StringBuilder Compose(StringBuilder textOutput)
        {
            int lastCC = 0;
            int lastStart = 0;

            for (int i = 0; i < textOutput.Length; i++)
            {
                int cc = Combining.GetClass(textOutput[i]);

                if ((i > 0) && ((lastCC == 0) || (lastCC != cc)))
                {
                    // Try to combine characters
                    char a = textOutput[lastStart];
                    char b = textOutput[i];
                    int c;

                    c = Hangul.Compose(a, b);
                    c = ((c == -1) ? Composition.Compose(a, b) : c);

                    if (c != -1)
                    {
                        textOutput[lastStart] = (char)c;
                        textOutput.Remove(i, 1);
                        i--;

                        lastCC = ((i == lastStart) ? 0 : Combining.GetClass(textOutput[i - 1]));
                        continue;
                    } // if
                } // if

                if (cc == 0)
                    lastStart = i;
                lastCC = cc;
            } // for

            return textOutput;
        } // Compose
        #endregion
    }
}
